package com.olt.config;

import com.alibaba.fastjson.JSON;
import com.olt.dao.log.LogDao;
import com.olt.domain.log.OltLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import util.RequestUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;


@ControllerAdvice
public class LogConfig implements HandlerInterceptor, ResponseBodyAdvice<Object> {

    @Autowired
    LogDao logDao;

    private static final String LOGGER_ENTITY="_loggerEntity";

    private static final String LOGGER_TIME="_loggerTime";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        OltLog log=new OltLog();
        log.setSession(request.getRequestedSessionId());
        log.setClientIp(request.getRemoteAddr());
        log.setMethod(request.getMethod());
        log.setUrl(request.getRequestURI());
        log.setParmaData(request.getQueryString());
        log.setBodyData(RequestUtil.getBodyString(request));
        request.setAttribute(LOGGER_ENTITY,log);
        request.setAttribute(LOGGER_TIME,System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ServletServerHttpRequest sshr = (ServletServerHttpRequest) request;
        HttpServletRequest httpRequest = sshr.getServletRequest();
        Calendar cal = Calendar.getInstance();
        if(httpRequest.getAttribute(LOGGER_ENTITY) instanceof OltLog) {
            OltLog log = (OltLog) httpRequest.getAttribute(LOGGER_ENTITY);
            Long time = (Long) httpRequest.getAttribute(LOGGER_TIME);
            log.setResponseTime(System.currentTimeMillis() - time);
            log.setReturnData(JSON.toJSONString(body));
            log.setPostTime(cal.getTime());

            logDao.save(log);
        }
        return body;
    }



}
